using System;
using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Extensions.Logging;
using RBAC.Domain.Dto.Output;
using RBAC.Domain.OutboundManage;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.OutboundManagement;

namespace RBAC.Write.Api.Application.Handler.ERP.OutboundManagement
{
    public class AppOrUnappSalesOutboundHandler : IRequestHandler<AppOrUnappSalesOutboundCommand, APIResult<bool>>
    {
        private readonly IBaseRepository<SalesOutbound> outboundRepo;
        private readonly ILogger<AppOrUnappSalesOutboundHandler> logger;

        public AppOrUnappSalesOutboundHandler(
            IBaseRepository<SalesOutbound> outboundRepo,
            ILogger<AppOrUnappSalesOutboundHandler> logger)
        {
            this.outboundRepo = outboundRepo;
            this.logger = logger;
        }

        public Task<APIResult<bool>> Handle(AppOrUnappSalesOutboundCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<bool>();
            try
            {
                var target = (request.Status ?? string.Empty).Trim();
                if (target != "审批" && target != "开立")
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "Status 仅支持：审批 / 开立";
                    result.Data = false;
                    return Task.FromResult(result);
                }

                var header = outboundRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = false", new { Id = request.Id });
                if (header == null)
                {
                    result.Code = APIEnums.Fail;
                    result.Msg = "单据不存在";
                    result.Data = false;
                    return Task.FromResult(result);
                }

                var current = (header.OrderStatus ?? string.Empty).Trim();
                if (target == "审批")
                {
                    if (!string.Equals(current, "开立", StringComparison.OrdinalIgnoreCase))
                    {
                        result.Code = APIEnums.Fail;
                        result.Msg = "仅开立状态可审批";
                        result.Data = false;
                        return Task.FromResult(result);
                    }
                }
                else if (target == "开立")
                {
                    if (!string.Equals(current, "审批", StringComparison.OrdinalIgnoreCase))
                    {
                        result.Code = APIEnums.Fail;
                        result.Msg = "仅审批状态可反审为开立";
                        result.Data = false;
                        return Task.FromResult(result);
                    }
                }

                var sql = @"START TRANSACTION;
UPDATE SalesOutbound SET OrderStatus=@Status WHERE Id=@Id AND IsDeleted=false;
COMMIT; SELECT 1;";
                try
                {
                    var ok = outboundRepo.QueryFirstOrDefault<int>(sql, new { Id = request.Id, Status = target });
                    result.Code = APIEnums.Success;
                    result.Msg = target == "审批" ? "审批成功" : "反审成功";
                    result.Data = ok == 1;
                }
                catch (Exception ex)
                {
                    outboundRepo.Execute("ROLLBACK;");
                    logger.LogError(ex, "设置出库单状态失败: {Message}", ex.Message);
                    result.Code = APIEnums.Error;
                    result.Msg = "设置出库单状态失败";
                    result.Data = false;
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "设置出库单状态异常: {Message}", ex.Message);
                result.Code = APIEnums.Error;
                result.Msg = "设置出库单状态异常";
                result.Data = false;
            }

            return Task.FromResult(result);
        }
    }
}
